package com.tongda.core.repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.tongda.core.common.Constants;
import com.tongda.core.utils.DBHelper;
import com.tongda.core.vo.MessageVO;

public class MessageDAO {
	// CREATE TABLE message ( id INTEGER PRIMARY KEY AUTOINCREMENT, name
	// VARCHAR( 60 ) DEFAULT ( '' ), [from] VARCHAR( 60 ) DEFAULT ( '' ),type
	// INT DEFAULT ( 0 ),call_type INT DEFAULT ( 0 ), content BLOB DEFAULT ( 1
	// ), status VARCHAR( 100 ) DEFAULT ( '' ), [desc] VARCHAR( 100 ) DEFAULT (
	// '' ), mes_time VARCHAR( 100 ) DEFAULT ( '' ), tabbleNo VARCHAR( 100 )
	// DEFAULT ( '' ),serial_no VARCHAR( 100 ) DEFAULT ( '' ));
	private String TABLE_NAME = "message";
	private DBHelper dbHelper;
	private SQLiteDatabase db;
	private static MessageDAO instance;

	public MessageDAO(Context context) {
		this.dbHelper = DBHelper.getInstance(context);
	}

	public MessageDAO() {

	}

	public static synchronized MessageDAO getInstance(Context context) {
		if (instance == null) {
			instance = new MessageDAO(context);
		}
		return instance;
	}

	public ArrayList<MessageVO> getAllMessages() {
		ArrayList<MessageVO> messages = new ArrayList<MessageVO>();
		try {
			db = dbHelper.getReadableDatabase();
			// Cursor cursor = db.rawQuery("select * from " + TABLE_NAME +
			// " where 1 = 1", new String[] { String.valueOf(0) });
			Cursor cursor = db.rawQuery("select * from " + TABLE_NAME, null);
			while (cursor.moveToNext()) {
				MessageVO message = new MessageVO();
				message.setName(cursor.getString(cursor.getColumnIndex("name")));
				message.setFrom(cursor.getString(cursor.getColumnIndex("from")));
				message.setDesc(cursor.getString(cursor.getColumnIndex("desc")));
				message.setType(cursor.getInt(cursor.getColumnIndex("type")));
				message.setContent(cursor.getString(cursor
						.getColumnIndex("content")));
				messages.add(message);
			}
			cursor.close();
		} catch (Exception e) {
			Log.e(this.toString(), e.getMessage());
		}
		return messages;
	}

	public ArrayList<MessageVO> getMessagesByParams(Map<String, String> params)
			throws Exception {
		ArrayList<MessageVO> messages = new ArrayList<MessageVO>();
		String selection = " 1 = 1 ";
		List<String> selectionArgsList = null;
		if (params != null) {
			selectionArgsList = new ArrayList<String>();
			Set<String> keys = params.keySet();
			for (String key : keys) {
				Object value = params.get(key);
				String operator = "=";
				if (value != null) {
					String[] valueArray = value.toString().split("_");
					if (valueArray.length == 1) {
						selectionArgsList.add(value.toString());
					} else if (valueArray.length == 2) {
						operator = valueArray[0];
						selectionArgsList.add(valueArray[1] + "");
					}
				}
				selection += " and " + key + "  " + operator + "? ";
			}
		}
		String[] selectionArgs = selectionArgsList.toArray(new String[] {});
		try {
			db = dbHelper.getReadableDatabase();
			String groupBy = null;
			String having = null;
			String orderBy = " mes_time desc ";
			String limit = null;
			// Cursor cursor = db.rawQuery("select * from " + TABLE_NAME+
			// " where 1 = 1 and type =" , new String[] { String.valueOf(0) });
			Cursor cursor = db.query(TABLE_NAME, null, selection,
					selectionArgs, groupBy, having, orderBy, limit);
			while (cursor.moveToNext()) {
				MessageVO message = new MessageVO();
				message.setId(cursor.getInt(cursor.getColumnIndex("id")));
				message.setName(cursor.getString(cursor.getColumnIndex("name")));
				message.setFrom(cursor.getString(cursor.getColumnIndex("from")));
				message.setDesc(cursor.getString(cursor.getColumnIndex("desc")));
				message.setType(cursor.getInt(cursor.getColumnIndex("type")));
				message.setCallType(cursor.getString(cursor
						.getColumnIndex("call_type")));
				message.setContent(cursor.getString(cursor
						.getColumnIndex("content")));
				message.setTime(cursor.getString(cursor
						.getColumnIndex("mes_time")));
				message.setStatus(cursor.getString(cursor
						.getColumnIndex("status")));
				message.setSerialNo(cursor.getString(cursor
						.getColumnIndex("serial_no")));
				message.setNotificationId(cursor.getInt(cursor
						.getColumnIndex("notificationId")));
				messages.add(message);
			}
			cursor.close();
		} catch (Exception e) {
			Log.e(this.toString(), e.getMessage());
			throw e;
		}
		return messages;
	}

	/**
	 * 修改对象
	 * 
	 * @param key
	 * @param value
	 */
	public void updateMessageStatus(MessageVO message) {
		try {
			db = dbHelper.openDatabase();
			ContentValues values = new ContentValues();
			values.put("[status]", "1");
			// db.execSQL("update message set status=? where id=?", new
			// Object[]{"1", message.getId()});
			db.update("message", values, "id=?", new String[] { message.getId()
					+ "" });
		} catch (Exception e) {
			e.printStackTrace();
		}
		dbHelper.closeDatabase();
	}

	/**
	 * 修改对象
	 * 
	 * @param key
	 * @param value
	 */
	public void deleteMessage(MessageVO message) {
		try {
			db = dbHelper.openDatabase();
			db.execSQL("delete from message  where id=?",
					new Object[] { message.getId() });
		} catch (Exception e) {
			e.printStackTrace();
		}
		dbHelper.closeDatabase();
	}

	/**
	 * 修改对象
	 * 
	 * @param key
	 * @param value
	 */
	public void deleteMessageBySerialNo(MessageVO message) {
		try {
			db = dbHelper.openDatabase();
			db.execSQL("delete from message  where serial_no=?",
					new Object[] { message.getSerialNo() });
		} catch (Exception e) {
			e.printStackTrace();
		}
		dbHelper.closeDatabase();
	}

	public void deleteMessageByTabNo(MessageVO message) {
		synchronized (Constants.objectLock) {
			try {
				db = dbHelper.openDatabase();
				db.execSQL("delete from message  where tabbleNo=?",
						new Object[] { message.getFrom() });
			} catch (Exception e) {
				e.printStackTrace();
			}
			dbHelper.closeDatabase();
		}
	}

	/**
	 * 修改对象
	 * 
	 * @param key
	 * @param value
	 */
	public void deleteAllMessage() {
		try {
			db = dbHelper.openDatabase();
			db.execSQL("delete from message  ");
		} catch (Exception e) {
			e.printStackTrace();
		}
		dbHelper.closeDatabase();
	}

	/**
	 * 插入对象
	 * 
	 * @param key
	 * @param value
	 */
	public void insertMessage(MessageVO message) {
		try {
			db = dbHelper.openDatabase();
			ContentValues values = new ContentValues();
			values.put("[from]", message.getFrom());
			values.put("name", message.getFrom());
			values.put("type", message.getFrom());
			values.put("content", message.getFrom());
			values.put("[time]", message.getFrom());
			values.put("[desc]", message.getFrom());
			db.insert(TABLE_NAME, null, values);
		} catch (Exception e) {
			e.printStackTrace();
		}
		dbHelper.closeDatabase();
	}

	/**
	 * 插入一条消息
	 * 
	 * @param key
	 * @param value
	 */
	public void insert(String key[], String value[]) {
		db = dbHelper.openDatabase();
		ContentValues values = new ContentValues();
		for (int i = 0; i < key.length; i++) {
			values.put(key[i], value[i]);
		}
		db.insert(TABLE_NAME, null, values);
		 dbHelper.closeDatabase();
	}

	@Deprecated
	public void insertMes() {
		db = dbHelper.openDatabase();
		db.execSQL("insert into message ( `name`, `desc`) values (?,?)",
				new Object[] { new Date().toLocaleString(), this });
		 dbHelper.closeDatabase();
	}

	public int countUnProcessMes() {
		synchronized (Constants.objectLock) {
			int count = 0;
			try {
				db = dbHelper.getReadableDatabase();
				// Cursor cursor = db.rawQuery("select * from " + TABLE_NAME +
				// " where 1 = 1", new String[] { String.valueOf(0) });
				Cursor cursor = db.rawQuery("select count(*) count  from "
						+ TABLE_NAME + " ", null);
				while (cursor.moveToNext()) {
					count = cursor.getInt(cursor.getColumnIndex("count"));
				}
				cursor.close();
//				dbHelper.closeDatabase();
			} catch (Exception e) {
				Log.e(this.toString(), e.getMessage());
			}
			return count;
		}
	}

}
